package cn.whr.server1.service.impl;

import cn.whr.server1.entity.CodeEntity;
import cn.whr.server1.entity.ResponseDTO;
import cn.whr.server1.entity.UserEntity;
import cn.whr.server1.repository.CodeRepository;
import cn.whr.server1.repository.UserRepository;
import cn.whr.server1.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CodeRepository codeRepository;

//    @Value("${version}") TODO bootstrap.yml配置连不上springconfig  ,springconfig工程拿得到值
//    private String v;

    @Override
    public ResponseDTO Registration(UserEntity user) {

        String name = user.getName();
        String phone = user.getPhone();

        if (name==null || phone==null) {
            return new ResponseDTO("ERROR", "用户名或密码有误,请重新输入!");
        }

        UserEntity existUser = userRepository.findRegisteredByName(name);

        if (existUser== null) {
            // TODO 通过配置取到多个值,随机取出一个
            String code = "6666";
            Long failureTime = new Date().getTime() + 2*60*1000L;// 暂定两分钟

            // TODO 发送短信  phone+code

            CodeEntity codeEntity = new CodeEntity();
            codeEntity.setCode(code);
            codeEntity.setName(name);
            codeEntity.setPhone(phone);
            codeEntity.setFailureTime(failureTime);

            codeRepository.save(codeEntity);

            return new ResponseDTO("SUCCESS", "短信已发送!");
        } else {
            return new ResponseDTO("ERROR", "用户名已存在,请重新输入!");
        }

    }

    @Override
    public ResponseDTO RegistrationEnd(UserEntity user, String code) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String name = user.getName();
        String phone = user.getPhone();

        CodeEntity codeData = codeRepository.findByNameAndPhone(name, phone);

        if (userRepository.findRegisteredByName(name) != null) {
            return new ResponseDTO("ERROR", "该账号已被注册,返回第一步!");
        }

        if (codeData == null) {
            return new ResponseDTO("ERROR", "请输入正确帐号或电话!");
        }

        if (codeData.getFailureTime() < new Date().getTime()) {
            return new ResponseDTO("ERROR", "CODE已过期,返回第一步!");
        }

        if (!codeData.getCode().equals(code)) {
            return new ResponseDTO("ERROR", "请输入正确验证码!");
        }

        user.setPwd(EncoderByMd5(user.getPwd()));

        // 验证是否注册
        if (userRepository.findRegisteredByName(name) == null) {
            userRepository.save(user);
            codeRepository.deleteByName(name);
            return new ResponseDTO("SUCCESS", "注册成功,进入登录页面!");
        } else {
            return new ResponseDTO("ERROR", "该账号已被注册,返回第一步!");
        }




    }

    @Override
    public ResponseDTO login(UserEntity user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        UserEntity existUser = userRepository.findRegisteredByName(user.getName());
        if (existUser == null) {
            return new ResponseDTO("ERROR", "登录失败,帐号不存在!");
        } else if (checkpassword(user.getPwd(), existUser.getPwd())) {
            return new ResponseDTO("SUCCESS", "登录成功!");
        } else {
            return new ResponseDTO("ERROR", "登录失败,帐号或密码错误!");
        }
    }

    /**利用MD5进行加密*/
    private String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5=MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }

    /**判断用户密码是否正确
     *newpasswd 用户输入的密码
     *oldpasswd 正确密码*/
    private boolean checkpassword(String newpasswd,String oldpasswd) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        if(EncoderByMd5(newpasswd).equals(oldpasswd))
            return true;
        else
            return false;
    }


}
